// Markdown
// We use GithubMarkdown to keep some of the HTML tags
var Markdown = require('markdown-to-html').GithubMarkdown;
// PDF
const HTML5ToPDF = require("html5-to-pdf");
const path = require("path");
// HTML
const fs = require('fs');


// Catch CLI Parameters
function getArgs () {
	// Source: https://stackoverflow.com/a/54098693
    const args = {};
    process.argv
        .slice(2, process.argv.length)
        .forEach( arg => {
        // long arg
        if (arg.slice(0,2) === '--') {
            const longArg = arg.split('=');
            const longArgFlag = longArg[0].slice(2,longArg[0].length);
            const longArgValue = longArg.length > 1 ? longArg[1] : true;
            args[longArgFlag] = longArgValue;
        }
        // flags
        else if (arg[0] === '-') {
            const flags = arg.slice(1,arg.length).split('');
            flags.forEach(flag => {
            args[flag] = true;
            });
        }
    });
    return args;
}
const args = getArgs();


// Markdown initiation
var md = new Markdown();
md.bufmax = 2048;
var fileName = 'test.md';
var opts = {title: 'File $BASENAME in $DIRNAME', stylesheet: 'style.css'};
var html = '';


// PDF conversion function
const convertToPDF = async (html) => {
	const html5ToPDF = new HTML5ToPDF({
		inputBody: html,
		outputPath: path.join(__dirname, "output.pdf"),
		pdf: {
			format: 'A4',
			margin: {
				top: '0.5in',
				bottom: '0.6in',
				right: '0.5in',
				left: '0.5in',
				},
			displayHeaderFooter:true,
			headerTemplate: '<div id="header-template"></div>',
			footerTemplate: '<div id="footer-template" style="font-size:10px !important; color:#808080; padding-left:10px; margin:10px auto;">Page <span class="pageNumber"></span></div>',
		},
		include: [
			path.join(__dirname, "style.css"),
		],
	});

	await html5ToPDF.start();
	await html5ToPDF.build();
	await html5ToPDF.close();
	console.log("PDF: DONE!");
	process.exit(0);
}


// source: https://stackoverflow.com/a/35893166
var streamToString = function(stream, callback) {
	var str = '';
	stream.on('data', function(chunk) {
		str += chunk;
	});
	stream.on('end', function() {
		callback(str);
	});
}


// Conversion from markdown code (and eventually to PDF)
md.render(fileName, opts, function(err) {
	if (err) {
		console.error('>>>' + err);
		process.exit();
	}
	// Write HTML and convert to PDF with the html retrieved
	streamToString(md, function(html) {
		if ( !(args['skip-pdf']) ) {
			try {
				convertToPDF(html)
			} catch (error) {
				console.error(error)
			}
		}
		if ( !(args['skip-html']) ) {
			fs.writeFile("output.html", html, function(err) {
				if (err) {
					return console.log(err);
				}
				console.log("HTML: DONE!");
			});
		}
	});
});
